#include "object.h"

#include <libxml/parser.h>
#include <libxml/tree.h>

#include "foreach.h"

namespace roperator{

void Object::load(std::wstring& file){
	load(wstr::toNonWide(file).c_str());
}
void Object::load(const char* file){
	xmlDocPtr doc;
	
	doc=xmlParseFile(file);
	if(!doc){
		throw ObjectXMLException(L"Failed to open document");
	}
	xmlNodePtr root=xmlDocGetRootElement(doc);
	if(!root){
		throw ObjectXMLException(L"No root element");
	}
	if(strcmp((char*)root->name, "object")){
		throw ObjectXMLException(L"Root element not object");
	}
	if(!xmlGetProp(root, (xmlChar*)"name")){
		throw ObjectXMLException(L"No name defined for object");
	}
	
	name=wstr::toWide((char*)xmlGetProp(root, (xmlChar*)"name"));
	
	for(xmlNodePtr node=xmlFirstElementChild(root); node!=NULL; node=xmlNextElementSibling(node)){
		//printf("%s %s\n",node->name, xmlGetProp(node, (xmlChar*)"name"));
		if(!strcmp((char*)node->name, "trigger")){
			if(!xmlGetProp(node, (xmlChar*)"name")){
				std::wcout << "Warning: object " << name << " has unnamed trigger - ignoring" << std::endl;
			}
			triggers[wstr::toWide((char*)xmlGetProp(node, (xmlChar*)"name"))]=wstr::toWide((char*)xmlNodeListGetString(doc, node->xmlChildrenNode, 1));
			//std::wcout << wstr::toWide((char*)xmlNodeListGetString(doc, node->xmlChildrenNode, 1)) << std::endl;
		}
	}
	/*xmlNodePtr node1=xmlFirstElementChild(root);
	xmlNodePtr node2=xmlNextElementSibling(node1);
	
	printf("%s\n",xmlGetProp(node1, (xmlChar*)"name"));
	printf("%s\n",xmlGetProp(node2, (xmlChar*)"name"));*/
}

void Object::dump(){
	
	std::wcout << L"--- Dumping object (or object class) '" << name << "' ---" << std::endl;
	
	if(!triggers.size())
		std::wcout << L"--- No triggers ---" << std::endl;
	else{
		std::wcout << L"--- Triggers ---" << std::endl;
		
		typedef std::pair<std::wstring, std::wstring> wstringpair;
		
		foreach(wstringpair p, triggers){
			std::wcout << L"\t--- Trigger '" << p.first << "' ---" << std::endl;
			std::wcout << p.second << std::endl;
		}
	}
}

}